package com.learn.demo;

import com.learn.demo.entity.Ctest;
import com.learn.demo.mapper.CtestMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;
import java.util.List;

/**
 * 单独集成Mybatis
 *
 * @author banjiawei
 * @date 2021/03/30
 */
@Slf4j
public class MybatisDemo {
    public static void main(String[] args) {
        BasicDataSource basicDataSource = new BasicDataSource();
        basicDataSource.setUrl("jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true");
        basicDataSource.setUsername("root");
        basicDataSource.setPassword("123456");
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("development", transactionFactory, basicDataSource);
        Configuration configuration = new Configuration(environment);
        configuration.addMapper(CtestMapper.class);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        try (SqlSession session = sqlSessionFactory.openSession()) {
            CtestMapper mapper = session.getMapper(CtestMapper.class);
            List<Ctest> ctests = mapper.getList();
            log.info("ctests is {}", ctests);
        }
    }
}
